package com.ms.config;

import com.sun.org.apache.xpath.internal.operations.Or;
import lombok.extern.log4j.Log4j;
import java.net.InetAddress;
import java.net.UnknownHostException;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.UNKNOWN;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;

@Component
@Log4j2
public class CutomGlobalFiter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String ip = getIP(request);
        log.info("=======================请求的ip地址"+ip);
        HttpHeaders headers = request.getHeaders();
        //拦截获取路径
        String path = request.getPath().toString();
        if (path.equals("/api/user/user/login")){
            //放行登陆
            System.out.println("=========登陆放行==========");
            return chain.filter(exchange);
        }else if(path.equals("/api/user/user/getYzm")){
            //放行登陆时获取图片验证码
            System.out.println("=========获取图片验证码放行==========");
            return chain.filter(exchange);
        }else if(path.equals("/api/content/bargainingitem/payy")){
            return chain.filter(exchange);
        }else if(path.equals("/api/content/bargainingitem/pay")){
            return chain.filter(exchange);
        }else if(path.equals("/api/content/goods/pay")){
            return chain.filter(exchange);
        }else{
            System.out.println("============其他路径需要进行token拦截============");
            List<String> token = request.getHeaders().get("token");
//            if (token == null){
//                throw new RuntimeException("拦截成功");
//            }else{
                System.out.println("------------------------");
                return chain.filter(exchange);
//            }
        }
    }


    // 多次反向代理后会有多个ip值 的分割符
    private final static String IP_UTILS_FLAG = ",";
    // 未知IP
    private final static String UNKNOWN = "unknown";
    // 本地 IP
    private final static String LOCALHOST_IP = "0:0:0:0:0:0:0:1";
    private final static String LOCALHOST_IP1 = "127.0.0.1";


    private static String getIP(ServerHttpRequest request){
        // 根据 HttpHeaders 获取 请求 IP地址
        String ip = request.getHeaders().getFirst("X-Forwarded-For");
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("x-forwarded-for");
            if (ip != null && ip.length() != 0 && !UNKNOWN.equalsIgnoreCase(ip)) {
                // 多次反向代理后会有多个ip值，第一个ip才是真实ip
                if (ip.contains(IP_UTILS_FLAG)) {
                    ip = ip.split(IP_UTILS_FLAG)[0];
                }
            }
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeaders().getFirst("X-Real-IP");
        }
        //兼容k8s集群获取ip
        if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
            if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
                //根据网卡取本机配置的IP
                InetAddress iNet = null;
                try {
                    iNet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    log.error("getClientIp error: ", e);
                }
                ip = iNet.getHostAddress();
            }
        }
        return ip;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
